package threading;

/**
 * @author krystal
 * @date 2022/11/25 9:04
 */
class MyBlockingQueue{
    private int[] items=new int[1000];
    private volatile int head=0;
    private volatile int tail=0;
    private volatile int size=0;

    //入队列
    public void put(int elem) throws InterruptedException {
        synchronized (this){
            //判定队列是否满了，满了则不能入队列
            while (size>=items.length){
                this.wait();
            }
            //进行插入操作，把elem放到items里，放到tail指向的位置
            items[tail]=elem;
            tail++;
            if (tail>=items.length){
                tail=0;
            }
            size++;
            this.notify();
        }
    }

    //出队列，返回删除元素的内容
    public Integer take() throws InterruptedException {
        synchronized (this){
            //判定队列是否空了，空了则不能出队列
            while (size==0){
                this.wait();
            }
            //进行取元素操作
            int ret=items[head];
            head++;
            if (head>=items.length){
                head=0;
            }
            size--;
            this.notify();
            return ret;
        }
    }
}

public class Demo23 {
    public static void main(String[] args) {
        MyBlockingQueue queue=new MyBlockingQueue();
        Thread producer=new Thread(()->{
            while (true){
                try {
                    int n=1;
                    queue.put(1);
                    System.out.println("生产元素"+n);
                    n++;
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread customer=new Thread(()->{
            while (true){
                try {
                    int n=queue.take();
                    System.out.println("消费元素"+n);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        producer.start();
        customer.start();
    }
}
